package com.woniuxy.classdeans.controller;

import com.woniuxy.classdeans.exception.ClassdeansException;
import com.woniuxy.classdeans.service.DropoutInfoService;
import com.woniuxy.classdeans.service.GradeDeanService;
import com.woniuxy.classdeans.service.StudentInfoService;
import com.woniuxy.classdeans.utils.WebSocketUtil;
import com.woniuxy.commons.entity.ResponseResult;
import com.woniuxy.commons.entity.wyh.DropoutInfo;
import com.woniuxy.commons.entity.wyh.GradeDean;
import com.woniuxy.commons.entity.wyh.ResponseTable;
import com.woniuxy.commons.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 退学信息处理
 *
 * @author 王艳辉
 * @date 2020/7/28 - 21:28
 */
@RestController
@RequestMapping("DropoutInfo")
@Slf4j
@Transactional
public class DropoutInfoController {
    @Autowired
    private DropoutInfoService dropoutInfoService;

    //redis的调用
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    //获取年级主任信息
    @Autowired
    private GradeDeanService gradeDeanService;

    //学生信息
    @Autowired
    private StudentInfoService studentInfoService;

    /**
     * 新增待处理信息
     *
     * @param stuid
     * @return
     */
    @RequestMapping("addDropoutInfo")
    public Object addDropoutInfo(int stuid) {
        //默认失败！
        ResponseResult res = new ResponseResult().setCode(400).setMessage("新增失败");

        try {
            int num = dropoutInfoService.addInfo(stuid, new Date());//新增信息
            if (num == 1) {
                return res.setMessage("新增成功");
            }
        } catch (Exception e) {
            log.error(e.getMessage());//日志记录
            //抛自定义异常
            throw new ClassdeansException("DropoutInfo/addDropoutInfo异常");
        }

        return res;

    }


    /**
     * 判断是否有消息
     *
     * @param req 请求对象
     * @return
     */
    @RequestMapping("judeHasMes")
    public Object judeHasMes(HttpServletRequest req) {
        //默认返回失败
        ResponseTable<DropoutInfo> res = new ResponseTable<DropoutInfo>(400, "获取信息失败");
        try {


            //获取token  查看的对应的用户的refreshToken
            String refreshToken = req.getHeader("refreshToken");
            System.out.println("获取到refreshToken为----------" + refreshToken);
            //验证是否存在token
//        if(refreshToken==null ||refreshToken.isEmpty()){
//            return res;
//        }
            //根据token去redis获取对应的详细信息 查询当前用户对应的map信息 包含：token  account role rid
            Map<Object, Object> entries = redisTemplate.opsForHash().entries(refreshToken);//测试
            //判断是否存在
            if (entries == null) {
                return res;
            }
            //获取用户的角色既teid
            int tcId = (int) entries.get("rid");

            //年级主任表查询年级主任全部信息
            GradeDean current = gradeDeanService.getByTcid(tcId);

            //获取所有的待审核信息
            List<DropoutInfo> all = dropoutInfoService.allDropoutInfo();

            //返回该年级主任待处理信息
            List<DropoutInfo> dropoutInfos = new ArrayList<DropoutInfo>();

            //遍历所有的待处理信息
            for (DropoutInfo cur : all) {

                //如果为当前年级主任的处理信息就加入到返回list中
                if (cur.getStudentInfo().getTeamInfo().getGradeInfo().getGradeType().equals(
                        current.getGradeInfo().getGradeType()
                )) {
                    dropoutInfos.add(cur);
                }
            }
            //获取用户token
            String token = (String) entries.get("token");
            //根据token获取uname
            String uname = JwtUtil.getUname(token);
            //如果存在未处理信息，调用websocket推送处理消息发送给指定用户
            if (dropoutInfos.size() > 0)
                WebSocketUtil.sendToTokenMessage(uname, "您有" + dropoutInfos.size() + "条未审核退学信息,请及时处理！");
            //返回数据
            res.setCode(0).setCount(dropoutInfos.size()).setMsg("获取成功").setData(dropoutInfos);
        } catch (Exception e) {

            log.error(e.getMessage());//日志记录
            //抛自定义异常
            throw new ClassdeansException("DropoutInfo/judeHasMes异常");

        }

        return res;
    }


    /**
     * 获取当前年级主任所有的退学审批信息
     *
     * @return
     */
    @RequestMapping("allDropoutInfo")
    public Object allDropoutInfo(HttpServletRequest req) {

        //默认返回失败
        ResponseTable<DropoutInfo> res = new ResponseTable<DropoutInfo>(400, "获取信息失败");

        try {
            //获取token  查看的对应的用户的refreshToken
            String refreshToken = req.getHeader("refreshToken");
            System.out.println("获取到refreshToken为----------" + refreshToken);
            //验证是否存在token
//        if(refreshToken==null ||refreshToken.isEmpty()){
//            return res;
//        }
            //根据token去redis获取对应的详细信息 查询当前用户对应的map信息 包含：token  account role rid
            Map<Object, Object> entries = redisTemplate.opsForHash().entries(refreshToken);//测试
            //判断是否存在
            if (entries == null) {
                return res;
            }
            //获取用户的角色既teid
            int tcId = (int) entries.get("rid");

            //年级主任表查询年级主任全部信息
            GradeDean current = gradeDeanService.getByTcid(tcId);

            //获取所有的待审核信息
            List<DropoutInfo> all = dropoutInfoService.allDropoutInfo();
            //如果该年级主任没有数据！自己返回
            if (all == null) return res;
            //返回该年级主任待处理信息
            List<DropoutInfo> dropoutInfos = new ArrayList<DropoutInfo>();

            //遍历所有的待处理信息
            for (DropoutInfo cur : all) {

                //如果为当前年级主任的处理信息就加入到返回list中
                if (cur.getStudentInfo().getTeamInfo().getGradeInfo().getGradeType().equals(
                        current.getGradeInfo().getGradeType()
                )) {
                    dropoutInfos.add(cur);
                }
            }
            //获取用户token
            String token = (String) entries.get("token");
            //根据token获取uname
            String uname = JwtUtil.getUname(token);
            //返回数据
            res.setCode(0).setCount(dropoutInfos.size()).setMsg("获取成功").setData(dropoutInfos);
        } catch (Exception e) {
            log.error(e.getMessage());//日志记录
            //抛自定义异常
            throw new ClassdeansException("DropoutInfo/allDropoutInfo异常");
        }

        return res;
    }

    /**
     * 审批是否通过
     *
     * @param stuid 班级信息
     * @param statu 修改后的状态
     * @return
     */
    @RequestMapping("updateDropoutStatu")
    public Object updateDropoutStatu(int stuid, int statu) {
        //默认返回失败
        ResponseTable<DropoutInfo> res = new ResponseTable<DropoutInfo>(400, "审批操作失败！");
        try {
            //1.修改退学信息表状态和修改审批时间
            int num = dropoutInfoService.updateDropoutStatu(stuid, statu);
            //2.如果审批通过，修改学生表信息

            if (num != 0 && statu == 2) { //审批通过
                num = studentInfoService.updateIsQuit(stuid);
                if (num == 1) {
                    return res.setCode(200).setMsg("审批成功！");
                }
            } else if (num != 0 && statu == 3) {//审批不通过
                return res.setCode(200).setMsg("审批不通过成功！");
            }
        } catch (Exception e) {
            log.error(e.getMessage());//日志记录
            //抛自定义异常
            throw new ClassdeansException("DropoutInfo/updateDropoutStatu异常");
        }

        return res;
    }

}
